# stories/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone


class CustomUser(AbstractUser):
    """自定义用户模型"""
    # 扩展用户信息
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="手机号")
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name="头像")
    bio = models.TextField(max_length=500, blank=True, null=True, verbose_name="个人简介")

    # 用户可以选择用户名或邮箱注册
    email = models.EmailField(unique=True, blank=True, null=True, verbose_name="邮箱")
    
    # 添加管理员标识字段
    is_admin = models.BooleanField(default=False, verbose_name="是否为管理员")

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"


class StoryCategory(models.Model):
    """故事分类模型"""
    name = models.CharField(max_length=50, unique=True, verbose_name="分类名称")
    description = models.TextField(blank=True, null=True, verbose_name="分类描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "故事分类"
        verbose_name_plural = "故事分类"


class Story(models.Model):
    """AI故事模型"""
    STATUS_CHOICES = (
        ('draft', '草稿'),
        ('pending', '待审核'),
        ('published', '已发布'),
        ('rejected', '已驳回'),
    )

    title = models.CharField(max_length=200, verbose_name="故事标题")
    detailed_description = models.TextField(blank=True, null=True, verbose_name="详细描述")
    content = models.TextField(verbose_name="故事内容")
    cover_image = models.ImageField(upload_to='story_covers/', blank=True, null=True, verbose_name="封面图片")
    category = models.ForeignKey(StoryCategory, on_delete=models.CASCADE, verbose_name="分类")
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="作者")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    view_count = models.IntegerField(default=0, verbose_name="浏览量")
    average_rating = models.FloatField(default=0.0, verbose_name="平均评分")
    rating_count = models.IntegerField(default=0, verbose_name="评分人数")
    
    # 审核相关字段
    reviewed_at = models.DateTimeField(null=True, blank=True, verbose_name="审核时间")
    reviewed_by = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.SET_NULL, 
                                   related_name='reviewed_stories', verbose_name="审核人")
    rejection_reason = models.TextField(blank=True, null=True, verbose_name="驳回原因")

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "故事"
        verbose_name_plural = "故事"
        ordering = ['-created_at']


class Comment(models.Model):
    """评论模型"""
    story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name='comments', verbose_name="故事")
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="评论者")
    content = models.TextField(verbose_name="评论内容")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='replies',
                               verbose_name="父评论")

    def __str__(self):
        return f"{self.author.username} - {self.story.title[:20]}"

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"
        ordering = ['created_at']


class Rating(models.Model):
    """评分模型"""
    story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name='ratings', verbose_name="故事")
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="评分用户")
    score = models.IntegerField(choices=[(i, i) for i in range(1, 6)], verbose_name="评分(1-5)")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return f"{self.user.username} - {self.story.title} - {self.score}星"

    class Meta:
        verbose_name = "评分"
        verbose_name_plural = "评分"
        unique_together = ('story', 'user')  # 每个用户对每个故事只能评一次分


class SensitiveWord(models.Model):
    """敏感词模型"""
    word = models.CharField(max_length=100, unique=True, verbose_name="敏感词")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")

    def __str__(self):
        return self.word

    class Meta:
        verbose_name = "敏感词"
        verbose_name_plural = "敏感词"
        ordering = ['word']